package com.huitone.gddw.controller.business;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huitone.gddw.controller.common.CommonController;
import com.huitone.gddw.dao.entity.SvrNodeDef;
import com.huitone.gddw.dao.entity.WebSmRec;
import com.huitone.gddw.log.Log;
import com.huitone.gddw.log.LogResult;
import com.huitone.gddw.log.LogType;
import com.huitone.gddw.dao.entity.SendSm;
import com.huitone.gddw.model.support.Message;
import com.huitone.gddw.service.ISvrNodeDefService;
import com.huitone.gddw.service.business.ISendSmService;
import com.huitone.gddw.service.business.IWebSmRecService;
import com.huitone.gddw.utils.ContextPropertiesUtils;

/**
 * 门户短信发送记录 控制器
 * @author wuluodan
 *
 */
@Controller
@RequestMapping(value="webSmRec")
public class WebSmRecController extends CommonController {

	private final static Logger LOGGER = Logger.getLogger(WebSmRecController.class);
	
	@Autowired
	private IWebSmRecService webSmRecService;
	
	@Autowired
	private ISvrNodeDefService svrNodeDefService;
	
	@Autowired
	private ISendSmService sendSmService;
	
	/**
	 * 保存
	 * @param entity WebSmRec
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="save")
	@Log(logType=LogType.UPDATE, content="单条短信发送")
	public Message save(WebSmRec entity, HttpServletRequest request) {
		try {
			WebSmRec webSmRec = webSmRecService.findUserLast();
			if (webSmRec != null && webSmRec.getSendTime() != null) {
				String smSendInterval = ContextPropertiesUtils.getProperty("sm_send_interval");
				if (new Date().getTime() - webSmRec.getSendTime().getTime() < Long.parseLong(smSendInterval) * 1000) {
					return new Message(false, "操作频繁！");
				}
			}
			
			if (StringUtils.isNotBlank(entity.getSvrNode())) {
				SvrNodeDef svrNodeDef = svrNodeDefService.selectByPrimaryKey(entity.getSvrNode());
				entity.setSendPort(svrNodeDef.getSendPort() + entity.getSendPort());
			}
			webSmRecService.save(entity);
			return new Message(true, monitorResult(entity));
		} catch (Exception e) {
			LOGGER.error("单条短信发送过程中出现异常：" + e.getMessage(), e);
			request.setAttribute("logResult", LogResult.EXCEPTION);
			return new Message(false, "发送异常！");
		}
	}
	
	/**
	 * 监听短信发送结果
	 * @param entity WebSmRec
	 * @return String 发送结果
	 */
	private String monitorResult(WebSmRec entity) {
		String[] arrSendCode = {"0", "ACCEPTD", "100", "DELIVRD"};
		List<String> listSendCode = Arrays.asList(arrSendCode);
		// 监听
		long maxDispatchTime = Long.parseLong(ContextPropertiesUtils.getProperty("sm_send_time")) * 1000;
		Date maxDate = new Date(new Date().getTime() + maxDispatchTime);
		SendSm sendSm = new SendSm();
		while (true) {
			if (new Date().after(maxDate)) {
				break;
			}
			sendSm = sendSmService.getBySmSeq(entity.getSmSeq());
			if (sendSm != null) {
				break;
			}
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		if (null == sendSm) {
			return "正在等待发送！";
		}
		if (StringUtils.isBlank(sendSm.getSendCode())) {
			return "已发送，未返回结果！";
		}
		if (listSendCode.contains(sendSm.getSendCode())) {
			return "发送成功！";
		}
		return "发送失败！";
	}
	
}
